package handler

import (
	"github.com/gin-gonic/gin"
	"news-mngr-sys/models"
	"news-mngr-sys/pkg"
	"strconv"
)

func Register(c *gin.Context) {
	tel := c.PostForm("tel")
	password := c.PostForm("password")
	user := models.User{
		Tel:      tel,
		Password: pkg.Md5str(password),
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "注册失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
	return
}
func Login(c *gin.Context) {
	tel := c.Query("tel")
	password := c.Query("password")
	var user models.User
	err := models.DB.Where("tel =?", tel).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	}
	if pkg.Md5str(password) != user.Password {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
	return
}
